package com.example.controller;

import com.example.entity.Article;
import com.example.service.ArticleService;
import com.example.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class ArticleController {

    @Autowired
    ArticleService articleService;

    @GetMapping("/article/add")
    public String add() {
        return "add";
    }

    @PostMapping("/article/add")
    public String addArticle(@RequestParam("title") String title, @RequestParam("content") String content) {
        articleService.add(title, content);
        return "redirect:/article/1";

    }

    @GetMapping("/article/update/{id}")
    public String update(Model model, @PathVariable Integer id) {
        Article article = articleService.selectById(id);
        model.addAttribute("article", article);
        return "update";
    }

    @PostMapping("/article/update/{id}")
    public String updateArticle(@PathVariable Integer id, @RequestParam("title") String title, @RequestParam("content") String content) {
        articleService.update(id, title, content);
        return "redirect:/article/1";

    }

    @GetMapping("article/delete/{id}")
    public String delete(@PathVariable Integer id) {
        articleService.deleteById(id);
        return "redirect:/article/1";
    }

    @GetMapping("/article/all")
    public String all(Model model) {
        List<Article> articles = articleService.selectAll();
        model.addAttribute("articles", articles);
        return "redirect:/article/1";
    }
    @GetMapping("/article/{page}")
    public String page(Model model, @PathVariable("page") int page){
        Page<Article> articlePage = articleService.findAllByPage(page-1, 2);
        int totalPages = articlePage.getTotalPages();
        List<Article> articles = articlePage.getContent();
        model.addAttribute("articles", articles);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("page", page);
        return "article";
    }

    @GetMapping("/")
    public String index(Model model){
        model.addAttribute("articles",articleService.selectAll());
        return "index";
    }

    @Autowired
    CommentService commentService;

//    @GetMapping("/article/content/{id}")
//    public String articleContent(@PathVariable Integer id,Model model){
//        model.addAttribute("article",articleService.selectById(id));
//        model.addAttribute("commentList",commentService.selectByAId(id));
//        return "content";
//    }
}

